package com.narata.netty.n3;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * @Author: XJL
 * @Description:
 * @Date: Create in 17:05 2022-05-04
 * @Modified By:
 **/
@Slf4j
public class CloseFutureClient {

    public static void main(String[] args) throws InterruptedException {

        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap().group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                nioSocketChannel.pipeline().addLast(new StringEncoder());
            }
        }).connect(new InetSocketAddress("localhost", 8080));

        Channel channel = channelFuture.sync().channel();
        new Thread(() -> {
            Scanner scanner = new Scanner(System.in);
            while (true) {
                String line = scanner.nextLine();
                if ( "q".equals(line)) {
                    channel.close(); // close异步操作
                    // 不能在这里善后
                    log.debug("处理关闭之后的操作");
                    break;
                }

                channel.writeAndFlush(line);
            }
        },"input").start();

        // 获取CloseFuture对象，（1）同步处理关闭 （2）异步处理关闭
        ChannelFuture closeFuture = channel.closeFuture();


//        closeFuture.sync();
//        log.debug("同步处理关闭之后的操作");

        closeFuture.addListener((ChannelFutureListener) channelFuture1 -> {
            log.debug("异步处理关闭之后的操作");
            group.shutdownGracefully();
        });
    }
}
